<?php
/**
 * 支付宝 - 面对面支付集成
 * comfiger
 * 2017-02-22
 **/
namespace Xijie\Model;
use Think\Model;

class AlipayModel extends Model{
	//定义表名称
	protected $tableName = 'paylog';
	//签名方式,默认为RSA2(RSA2048)
	private $sign_type = "RSA";
	//支付宝公钥
	private $alipay_public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChKhcYdsTsP2ORWsRIKG0TJUHTuPQHKJZMgQ/rVanVLxLJ/2G15wMqCzlliHoNupEuJg3Y6tFMVZyYuXRm2a7RKC6FybG1qldEQCpce5HDhptwWUJkGdp2VypztBmG3kqWRKq3aaZU/mQnA4qeNMewxzVBRKEW59Q2c7NRkBItSQIDAQAB";
	//商户私钥
	private $merchant_private_key = "MIICWwIBAAKBgQChKhcYdsTsP2ORWsRIKG0TJUHTuPQHKJZMgQ/rVanVLxLJ/2G15wMqCzlliHoNupEuJg3Y6tFMVZyYuXRm2a7RKC6FybG1qldEQCpce5HDhptwWUJkGdp2VypztBmG3kqWRKq3aaZU/mQnA4qeNMewxzVBRKEW59Q2c7NRkBItSQIDAQABAoGAfdWBRualBtjPgxRdoQF/eK1kYk1Mq7Iy9/TlWxf9jKg+gV1XC1IeFFvDKtWOht2esWug8DcXyAQoSs6yZgOdDBCVfVLADcmM5uZdYWS/7y+t+vO94j+1Rtlq5qSP+SviXzT3JMHqtOO0secESUNKWP5dRIBsI8DdJDrA2RN5HaECQQDPG4U7Swp/XH36a3LsCsSEMpx70Dr87cAmRHsrpNj1AdUH1pPQAPRceHdkXi3mBepYObX900aX/IiDrCe9hQ5lAkEAxzYDXeAv6FtrO5ahRIRI7LX/6YdiEYKlkVsowQQN/489nSIi2ryghyMUl6Xy0PSGAJEMHRYYXnySEmH6ORSTFQJAf6eb4GcpikUtVUwjYsBkToOPlnVL1piIxk2Rid4q6CF/+DvXke70r4aFOLUgH1boEgdIWLKAIbBDSL21JQi9TQJAduvMmLbjgo9IdXsXbIKX0g9X5T33kkJuulYz/v1/qccF3g7pxbCDGAkeGuVrDchbUm1EUPzGsWkl/ilVKcwZfQJAPJWYC+2aYGw2UfdqWtJqcbdcKXMORUc+m/oHMbuHMZUGq9cWlIl+5y+mX5NTw/Zu3T4Kzp9xOX4G32gA0eFMqQ==";
	//编码格式
	private $charset = "UTF-8";
	//支付宝网关
	private $gatewayUrl = "https://openapi.alipay.com/gateway.do";
	//商家ID
	private $pid = "2088221031529168";
	//应用ID
	private $app_id = "2016032101230837";
	//异步通知地址,只有扫码支付预下单可用
	private $notify_url = "http://mamagy.com/xj/pay/alipay.html";
	//最大查询重试次数
	private $MaxQueryRetry = 10;
	//查询间隔
	private $QueryDuration = 3;
	
	//支付宝RSA私钥地址
	protected $rsaPrivateKeyFilePath = "./Public/rsa/rsa_private_key.pem"; 
	//支付宝公钥地址
	protected $rsaPublicKeyFilePath = "./Public/rsa/rsa_public_key.pem"; 
	
	/**
	 * 创建订单
	 **/
	public function createAction($array){
        Vendor('aop.AopClient');  
        Vendor('aop.signData');
        Vendor('aop.AlipayTradePrecreateRequest');  #如果你没有把这个文件提出来，就应该是aop.request.AlipayTradePrecreateRequest
        $aop = new \AopClient();
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = $this->app_id;
        $aop->rsaPrivateKeyFilePath = $this->rsaPrivateKeyFilePath;
        $aop->alipayPublicKey = $this->rsaPublicKeyFilePath;
        $aop->apiVersion = '1.0';
        $aop->postCharset='UTF-8';
        $aop->format='json'; 
        $request = new \AlipayTradePrecreateRequest();
		
       // $data = json_encode($array, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
		$data = json_encode($array);
		
        $request->setBizContent($data);
		$request->setNotifyUrl($this->notify_url);
		
        $result = $aop->execute ($request); 
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        
		if(!empty($resultCode)&&$resultCode == 10000){
            $resp = (array)$result->$responseNode;
			return $resp;
        } else {
            echo "失败";
            exit;
        }
    }
	
	/**
	 * 支付宝支付订单创建
	 **/
	public function createWapAction($array, $notify_url='http://mamagy.com/xj/wap/alinotify.html'){
        Vendor('aop.AopClient');  
        Vendor('aop.signData');
        Vendor('aop.AlipayTradeWapPayRequest');  #如果你没有把这个文件提出来，就应该是aop.request.AlipayTradePrecreateRequest
        $aop = new \AopClient();
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = $this->app_id;
        $aop->rsaPrivateKeyFilePath = $this->rsaPrivateKeyFilePath;
        $aop->alipayPublicKey = $this->rsaPublicKeyFilePath;
        $aop->apiVersion = '1.0';
        $aop->postCharset='UTF-8';
        $aop->format='json'; 
        $request = new \AlipayTradeWapPayRequest();
		
        //$data = json_encode($array, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
		$data = json_encode($array);
		
        $request->setBizContent($data);
		$request->setNotifyUrl($notify_url);

		//$request->setReturnUrl('http://mamagy.com/xj/wap/cost.html');

        $result = $aop->pageExecute($request, "post");
		
		print("<pre>");
		print_r($result);
		exit;
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
       
		if(!empty($resultCode)&&$resultCode == 10000){
            $resp = (array)$result->$responseNode;
			return $resp;
        }
    }
	
	/**
	 * 验证订单是否为支付宝返回
	 * @param string $notify_id
	 **/
	public function checkAlipayNotifyId($notify_id){
		$checkUrl = 'https://mapi.alipay.com/gateway.do?service=notify_verify&partner='. $this->app_id .'&notify_id='. $notify_id;
		$content = file_get_contents($checkUrl);
		if($content == 'true' || $content == true){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 判断卖家信息是否正确
	 * @param string $seller_id 商户ID
	 * @param string $seller_email 商户账号
	 **/
	public function checkSellerInfo($seller_id, $seller_email){
		if($seller_id == $this->app_id && $seller_email == $this->seller_id){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * RSA签名
	 **/
	private function alipaySign($data){
		//读取私钥文件
		$priKey = "-----BEGIN RSA PRIVATE KEY-----\n" .
				wordwrap($this->merchant_private_key, 64, "\n", true) .
				"\n-----END RSA PRIVATE KEY-----";
		//转换为openssl密钥,必须是没有经过pkcs8转换的密钥
		$res = openssl_get_privatekey($priKey);
		//调用openssl内置签名方法，生成签名
		openssl_sign($data, $sign, $res);
		//释放资源
		openssl_free_key($res);
		//base64编码
		$sign = base64_encode($sign);
		return $sign;
	}
	
	/**
	 * RSA验证签名
	 *
	 **/
	private function alipayVerify($prestr, $sign){
		$sign = base64_decode($sign);
		$public_key = "-----BEGIN RSA PUBLIC KEY-----\n" .
				wordwrap($this->alipay_public_key, 64, "\n", true) .
				"\n-----END RSA PUBLIC KEY-----";
		$pkeyid = openssl_get_publickey($public_key);
		if($pkeyid){
			$verify = openssl_verify($prestr, $sign, $pkeyid);
			openssl_free_key($pkeyid);
		}
		
		if($verify == 1){
			return true;
		}else{
			return false;
		}
	}
	
	private function curl($url, $postFields = null) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_FAILONERROR, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

		$postBodyString = "";
		$encodeArray = Array();
		$postMultipart = false;

		if (is_array($postFields) && 0 < count($postFields)) {
			foreach ($postFields as $k => $v) {
				if ("@" != substr($v, 0, 1)) //判断是不是文件上传
				{
					$postBodyString .= "$k=" . urlencode($this->characet($v, $this->postCharset)) . "&";
					$encodeArray[$k] = $this->characet($v, $this->postCharset);
				} else //文件上传用multipart/form-data，否则用www-form-urlencoded
				{
					$postMultipart = true;
					$encodeArray[$k] = new \CURLFile(substr($v, 1));
				}
			}
			unset ($k, $v);
			curl_setopt($ch, CURLOPT_POST, true);
			if ($postMultipart) {
				curl_setopt($ch, CURLOPT_POSTFIELDS, $encodeArray);
			} else {
				curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));
			}
		}

		if ($postMultipart) {
			$headers = array('content-type: multipart/form-data;charset=UTF-8;boundary=' . $this->getMillisecond());
		} else {
			$headers = array('content-type: application/x-www-form-urlencoded;charset=UTF-8');
		}
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		$reponse = curl_exec($ch);
		if (curl_errno($ch)) {
			throw new Exception(curl_error($ch), 0);
		} else {
			$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			if (200 !== $httpStatusCode) {
				//throw new Exception($reponse, $httpStatusCode);
			}
		}
		curl_close($ch);
		return $reponse;
	}
}
